import React, { useEffect } from 'react';
// @ts-ignore
import { PlusCircleOutlined, FileTextOutlined, DownloadOutlined } from '#/utils/antdIcons';
import moment from 'moment';
import { DatePicker, Form, Space, Button, Select, message } from 'antd';
import type { IFormValue, IDealElementOptions, IDataListType } from '../../type';
import { IMaintenancePlanModalType } from '../../type';
import { DateHintText } from '../../dictionary';
import styles from './index.less';
import { useDebounceFn } from 'ahooks';

interface IProps {
  /**
   * 表单值
   */
  values?: IFormValue;
  /**
   * 省份数据
   */
  provinceOptions?: IDealElementOptions[];
  /**
   * 交易单元数据
   */
  dealElementOptions?: IDealElementOptions[];
  /**
   * 改变省份
   */
  onChangeProvince?: (params: IFormValue, children: any) => void;
  /**
   * 新增检修计划表
   */
  onAdd?: (record?: IDataListType, type?: IMaintenancePlanModalType, onReview?: any) => void;
  /**
   * 全部检修计划
   */
  previewYearlyPlans?: () => void;
  /**
   * 搜索数据
   */
  onSearch?: (values: IFormValue) => void;
  /**
   * 默认请求
   */
  defaultRequest?: () => void;
  /**
   * 导出检修计划
   */
  exportMaintenancePlan?: () => void;
  /**
   * 导出按钮权限
   */
  canEport?: boolean;
}

const Header = (props: IProps) => {
  const [form] = Form.useForm();
  const {
    values = {},
    provinceOptions = [],
    dealElementOptions = [],
    onSearch,
    onChangeProvince,
    onAdd,
    previewYearlyPlans,
    defaultRequest,
    exportMaintenancePlan,
    canEport,
  } = props;

  useEffect(() => {
    const { startDate, endDate, ...rest } = values;
    const _values = {
      date:
        startDate && endDate
          ? [moment(startDate), moment(endDate)]
          : [moment().add(1, 'day'), moment().add(1, 'day')],
      ...rest,
    };
    form && form.setFieldsValue(_values);
  }, [values]);

  // 改变省份
  const _onChangeProvince = (e: string, { stationId, children, provinceId }: any) => {
    onChangeProvince &&
      onChangeProvince(
        {
          provinceId: provinceId,
          marketId: e,
          stationId,
        },
        children,
      );
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { value, label } = option;
    return (
      value?.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  // 改变日期
  const onChangeDate = (date: any) => {
    const dayDiff = moment(moment(date[1])).diff(moment(date[0]), 'day') + 1;
    if (onAdd && previewYearlyPlans && dayDiff > 7) {
      message.warn(DateHintText);
    }
  };

  // 搜索
  const onFinish = (data: any) => {
    const { date, ...rest } = data;
    const _startDate = moment(date[0]).format('YYYY-MM-DD');
    const _endDate = moment(date[1]).format('YYYY-MM-DD');
    onSearch &&
      onSearch({
        ...rest,
        startDate: _startDate,
        endDate: _endDate,
      });
  };

  // 新建计划
  const _addMaintenancePlan = () => {
    const { stationId } = form && form.getFieldsValue();
    onAdd && onAdd({ stationId: stationId }, IMaintenancePlanModalType.ADD);
  };

  // 全部检修计划
  const _previewYearlyPlans = () => {
    previewYearlyPlans && previewYearlyPlans();
  };
  const _onReset = useDebounceFn(
    () => {
      defaultRequest && defaultRequest();
    },
    { wait: 500 },
  );

  return (
    <div className={styles.container}>
      <Form
        form={form}
        name="filter"
        requiredMark={false}
        colon={false}
        autoComplete="off"
        onFinish={onFinish}
      >
        <Form.Item name="marketId" rules={[{ required: true, message: '请选择省份' }]}>
          <Select
            placeholder={'请选择省份'}
            showArrow={true}
            style={{ width: 200 }}
            key="value"
            options={provinceOptions as any[]}
            showSearch={true}
            filterOption={filterOption as any}
            onChange={_onChangeProvince}
          />
        </Form.Item>
        <Form.Item noStyle name="provinceId" />
        <Form.Item name="stationId" rules={[{ required: true, message: '请选择交易单元' }]}>
          <Select
            style={{ width: 200 }}
            placeholder="请选择"
            showArrow={true}
            options={(dealElementOptions || []) as any}
            showSearch={true}
            filterOption={filterOption as any}
          />
        </Form.Item>
        <Form.Item name="date" rules={[{ required: true, message: '请选择时间' }]}>
          <DatePicker.RangePicker
            format={['YYYYMMDD', 'YYYYMMDD']}
            placeholder={['请选择', '请选择']}
            className={styles.datePicker}
            onChange={onChangeDate}
            separator="-"
          />
        </Form.Item>
        <Space size={'middle'}>
          <Button type="primary" htmlType="submit" className={styles.searchBtn}>
            查询
          </Button>
          <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
            重置
          </Button>
        </Space>
      </Form>
      {onAdd && previewYearlyPlans && exportMaintenancePlan && (
        <div className={styles.right}>
          <div
            className={`${styles.exportMaintenancePlan} ${canEport && styles.disabled}`}
            onClick={exportMaintenancePlan}
          >
            <DownloadOutlined />
            <span className={styles.exportText}>导出</span>
          </div>
          <div className={styles.addMaintenancePlan} onClick={_addMaintenancePlan}>
            <PlusCircleOutlined className={styles.addMaintenancePlanLogo} />
            <span className={styles.addMaintenancePlanText}>新建计划</span>
          </div>
          <div className={styles.yearlyPlans} onClick={_previewYearlyPlans}>
            <FileTextOutlined className={styles.yearlyPlansLogo} />
            <span className={styles.yearlyPlansText}>全部检修计划</span>
          </div>
        </div>
      )}
    </div>
  );
};

export default Header;
